//
//  NYRecommendViewController.m
//  Nooryes
//
//  Created by baken on 2020/2/19.
//  Copyright © 2020 MyApp. All rights reserved.
//

#import "NYRecommendViewController.h"
#import "NYRecommendViewModel.h"
#import "SDCycleScrollView.h"
#import "CustomLabel.h"
#import "NSString+dynamicSize.h"
#import "CHTCollectionViewWaterfallLayout.h"
#import "NYTopicCategoryModel.h"
#import "NYRecommendCollectionViewCell.h"
#import "NYArticleListModel.h"
#import "NYArticleDetailViewController.h"
#import "NYTopicListViewController.h"
#import "NYSearchViewController.h"
#import "NYRecommendSlideModel.h"
#import "WebViewController.h"
#import "NYTopicArticlesViewController.h"
#import "NYMainViewModel.h"
#import "TopicCategoryModel.h"
#import "NYMiniAdModel.h"
#import "NYPrivacyViewController.h"


@interface NYRecommendViewController ()<SDCycleScrollViewDelegate,UIScrollViewDelegate,UISearchBarDelegate,UICollectionViewDelegate,UICollectionViewDataSource,CHTCollectionViewDelegateWaterfallLayout>

@property (nonatomic, strong) SDCycleScrollView *adScrollView;

@property (nonatomic, strong) NYRecommendViewModel *recommendVM;

@property (nonatomic, strong) CHTCollectionViewWaterfallLayout *layout;

@property (weak, nonatomic) IBOutlet UIScrollView *topicScrollView;

@property (weak, nonatomic) IBOutlet UIView *sliderView;

@property (weak, nonatomic) IBOutlet UIView *topicView;

@property (weak, nonatomic) IBOutlet UIScrollView *backScrollView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topicViewWidth;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *collectionH;

@property (nonatomic, strong) CustomLabel *selectedLabel;

@property (nonatomic, assign) CGFloat caculateHeight;

@property (weak, nonatomic) IBOutlet UISearchBar *saerchBar;

@property (nonatomic, strong) NYMainViewModel *mainVM;
@property (weak, nonatomic) IBOutlet UIView *adView;

@property (weak, nonatomic) IBOutlet UIImageView *adImage;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *adheight;

@end

@implementation NYRecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"推荐";
    [self popProvacy];
    CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    self.collectionView.collectionViewLayout = layout;
    [self.collectionView registerClass:[NYRecommendCollectionViewCell class] forCellWithReuseIdentifier:kNYRecommendCollectionViewCell];
    
    
    self.saerchBar.layer.cornerRadius = 14;
    self.saerchBar.layer.masksToBounds = YES;
    
    [self.recommendVM getMiniAdWithCompletionHandle:^(NSError *error) {
        if (!error) {
            if (self.recommendVM.miniAD) {
                [self.adheight setConstant:95];
                [self.adImage sd_setImageWithURL:[NSURL URLWithString:self.recommendVM.miniAD.image]];
            } else {
                [self.adheight setConstant:0];
            }
        } else {
            [self.adheight setConstant:0];
        }
    }];
    
    [self.recommendVM getRecommendCategoryWithCompletionHandle:^(NSError *error) {
        if (!error) {
            [self setupTitle];
        }
    }];
    
    [self.recommendVM getRecommendSlideWithCompletionHandle:^(NSError *error) {
        if (!error) {
            [self.sliderView addSubview:self.adScrollView];
        }
    }];
    self.backScrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self.recommendVM refreshDataCompletionHandle:^(NSError *error) {
            [self.collectionView reloadData];
            [self.backScrollView.mj_header endRefreshing];
        }];
        
    }];
    self.backScrollView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self.recommendVM getMoreDataCompletionHandle:^(NSError *error) {
            [self.collectionView reloadData];
            [self.backScrollView.mj_footer endRefreshing];
        }];
    }];
    
    
    [self.backScrollView.mj_header beginRefreshing];
    [self popUpdateAlert];
    
    
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    RecommendSlideModel *model =[self.recommendVM.slideArray objectAtIndex:index];
    if ([model.type isEqualToString:@"1"]) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"RecommendStoryboard" bundle:nil];
        NYArticleDetailViewController *detailVC =[storyboard  instantiateViewControllerWithIdentifier:@"NYArticleDetailViewController"];
        detailVC.articleID = model.articleid;
        [self.navigationController pushViewController:detailVC animated:YES];
        
    } else if ([model.type isEqualToString:@"2"]){
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:model.link] options:[NSDictionary dictionary] completionHandler:nil];
    }
}
- (IBAction)onMiniAd:(id)sender {
    //type 1内部 2外部
    if ([self.recommendVM.miniAD.type isEqualToString:@"1"]) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"RecommendStoryboard" bundle:nil];
        NYArticleDetailViewController *detailVC =[storyboard  instantiateViewControllerWithIdentifier:@"NYArticleDetailViewController"];
        detailVC.articleID = self.recommendVM.miniAD.articleid;
        [self.navigationController pushViewController:detailVC animated:YES];
        
    } else if ([self.recommendVM.miniAD.type isEqualToString:@"2"]){
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.recommendVM.miniAD.link] options:[NSDictionary dictionary] completionHandler:nil];
    }
}

- (void)setupTitle {
    CGFloat totalWidth = 0;
    for (NSInteger i = 0; i < self.recommendVM.topicArray.count; i++) {
        CustomLabel *label = [[CustomLabel alloc] init];
        TopicCategoryModel *model = self.recommendVM.topicArray[i];
        label.text = model.name;
        
        CGFloat width = [model.name dynamicWidthWithFontSize:15 andCGSize:CGSizeMake(MAXFLOAT, 17) andLineSpace:0].width +20;
        
        CGFloat labelX = totalWidth;
        totalWidth += width;
        label.frame = CGRectMake(labelX, 0, width, 30);
        [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelClick:)]];
        label.tag = i;
        [self.topicView addSubview:label];
        
        if (i == 0) { // 最前面的label
            label.scale = 1.0;
            self.selectedLabel = label;
        }
    };
    [self.topicViewWidth setConstant:totalWidth];
    
}


/**
 * 监听顶部label点击
 */
- (void)labelClick:(UITapGestureRecognizer *)tap{
    //    self.selectedLabel.scale = 0.0;
    CustomLabel *label = (CustomLabel *)tap.view;
    //    label.scale = 1.0;
    self.selectedLabel = label;
    CGPoint titleOffset = self.topicScrollView.contentOffset;
    titleOffset.x = label.center.x - kScreenWidth * 0.5;
    CGFloat maxTitleOffsetX = self.topicViewWidth.constant - kScreenWidth;
    // 左边超出处理
    if (titleOffset.x < 0) {
        titleOffset.x = 0;
    } else if (titleOffset.x >maxTitleOffsetX){// 右边超出处理
        titleOffset.x = maxTitleOffsetX;
    }
    [self.topicScrollView setContentOffset:titleOffset animated:YES];
    
    TopicCategoryModel *model = self.recommendVM.topicArray[label.tag];
    if (![model.talkid isEqualToString:@"999"]) {
        UIStoryboard *board = [UIStoryboard storyboardWithName:@"TopicStoryboard" bundle:nil];
        if ([model.talkid isEqualToString:@"0"]) {
            NYTopicListViewController *listVC = [board instantiateViewControllerWithIdentifier:@"NYTopicListViewController"];
            listVC.topicID = model.talkid;
            [self.navigationController pushViewController:listVC animated:YES];
        } else{
            NYTopicArticlesViewController *listVC = [board instantiateViewControllerWithIdentifier:@"NYTopicArticlesViewController"];
            listVC.topicID = model.talkid;
            [self.navigationController pushViewController:listVC animated:YES];
        }
        
    }
    
}


-(SDCycleScrollView *)adScrollView{
    if (!_adScrollView) {
        _adScrollView = [SDCycleScrollView cycleScrollViewWithFrame:self.sliderView.bounds delegate:self placeholderImage:nil];
        _adScrollView.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _adScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
        _adScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
        _adScrollView.autoScrollTimeInterval = 3.0f;
        _adScrollView.imageURLStringsGroup = [self.recommendVM.slideImageArray copy];
    }
    return _adScrollView;
}



#pragma mark UIScrollerView Delegate


//scrollView滚动就会调用此方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
}
#pragma mark - UICollectionView Delegate


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.recommendVM.dataArr.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NYRecommendCollectionViewCell *cell = [NYRecommendCollectionViewCell cellWithCollectionView:collectionView indePath:indexPath];
    ArticleListModel *model = [self.recommendVM.dataArr objectAtIndex:indexPath.row];
    cell.model = model;
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.image] placeholderImage:[UIImage imageNamed:@"loading"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (image) {
            if (!CGSizeEqualToSize(model.imageSize, image.size)) {
                model.imageSize = image.size;
                [collectionView reloadItemsAtIndexPaths:@[indexPath]];
            }
        }
    }];
    
    return cell;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ArticleListModel *model = [self.recommendVM.dataArr objectAtIndex:indexPath.row];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"RecommendStoryboard" bundle:nil];
    NYArticleDetailViewController *detailVC =[storyboard  instantiateViewControllerWithIdentifier:@"NYArticleDetailViewController"];
    detailVC.articleID = model.articleid;
    [self.navigationController pushViewController:detailVC animated:YES];
}



#pragma mark - CHTCollectionViewDelegateWaterfallLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    ArticleListModel *model = [self.recommendVM.dataArr objectAtIndex:indexPath.row];
    if (!CGSizeEqualToSize(model.imageSize, CGSizeZero)) {
        return model.imageSize;
    }
    
    if (indexPath.item == self.recommendVM.dataArr.count - 1 ) {
        [self.collectionH setConstant:self.collectionView.contentSize.height+80];
    }
    return CGSizeMake(150, 150);
}

#pragma mark UISearchBar Delegate


-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    
    NYSearchViewController *searchViewController = [[NYSearchViewController alloc] initWithNibName:@"NYSearchViewController" bundle:nil];
    [self.navigationController pushViewController:searchViewController animated:YES];
    
    //    NYNewSearchViewController *searchViewController = [[NYNewSearchViewController alloc] initWithNibName:@"NYNewSearchViewController" bundle:nil];
    //      [self.navigationController pushViewController:searchViewController animated:YES];
    
    return NO;
}

-(NYMainViewModel *)mainVM{
    if (!_mainVM) {
        _mainVM = [NYMainViewModel new];
    }
    return _mainVM;
}


-(NYRecommendViewModel *)recommendVM{
    if (!_recommendVM) {
        _recommendVM = [NYRecommendViewModel new];
    }
    return _recommendVM;
}

- (void)popUpdateAlert{
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [self.mainVM checkVersionWithConplationHandle:^(NSError *error) {
        if (!error) {
            if (![self.mainVM.versionModel.version isEqualToString:currentVersion]) {
                NSMutableString *mutStr = [[NSMutableString alloc] init];
                for (NSString *str in self.mainVM.versionModel.log) {
                    if (self.mainVM.versionModel.ismust) {
                        [mutStr appendString:@"本次更新强制执行，不更新程序即将退出"];
                        [mutStr appendString:@"\n"];
                    }
                    [mutStr appendString:str];
                    [mutStr appendString:@"\n"];
                }
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"新版本升级" message:mutStr preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.mainVM.versionModel.downurl] options: [NSDictionary dictionary] completionHandler:^(BOOL success) {
                    }];
                }]];
                [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    if (self.mainVM.versionModel.ismust) {
                        assert(0);
                    }
                }]];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }
    }];
}

-(void)popProvacy{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *agree = [defaults objectForKey:@"didAgree"];
    if (IsStrEmpty(agree)) {
        NYPrivacyViewController *privacyVC = [[NYPrivacyViewController alloc] initWithNibName:@"NYPrivacyViewController" bundle:nil];
        privacyVC.closeBlock = ^(BOOL b) {
            if (!b) {
                [self performSelector:@selector(notExistCall)];
                abort();
            }
        };
        [self presentViewController:privacyVC animated:YES completion:nil];
        //        privacyVC.view.frame = self.view.frame;
    }
}
@end
